<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocket</title>
</head>
<body>
<form action="" onsubmit="return false;">
    <input type="text" name="message" value="">
    <br>
    <input type="button" onclick="send(this.form.message.value)" value="发送webSocket消息">
    <hr color="red">
    <h2>客户端接收到服务端返回的消息</h2>
    <textArea id="responseContent" style="width: 1024px; height: 300px"></textArea>

</form>

<script type="text/javascript">
    let socket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }

    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8888/webSocket");
        socket.onmessage = function (event) {
            var ta = document.getElementById('responseContent');
            ta.value += event.data + '\r\n';
        };

        socket.onopen = function (event) {
            var ta = document.getElementById('responseContent');
            ta.value = '你当前的浏览器支持webSocket功能, 请继续 \r\n';
        };

        socket.onclose = function (event) {
            var ta = document.getElementById('responseContent');
            ta.value = '';
            ta.value = 'webSocket连接已经关闭\r\n';
        };

        function send(message) {
            if (!window.WebSocket) {
                return;
            }

            if (socket.readyState === WebSocket.OPEN) {
                socket.send(message);
            } else {
                alert('连接没有建立成功');
            }
        }
    } else {
        alert('你的浏览器不支持webSocket功能, 请到https://www.google.com/chrome下载支持webSocket功能的浏览器');
    }

</script>
</body>
</html>